const express = require('express')
const app = express()
app.listen(3000, function () {
    console.log('3000端口开启了，可以访问: http://localhost:3000')
})

const path = require('path')
const fs = require('fs')

app.use('/static', express.static('static'))
//开放静态资源

app.use(express.urlencoded({ extended: false }))
//接受post参数必备
////---------------------------------------------------------//
const serveFavicon = require('serve-favicon') 
//第三方中间件

//const { time } = require('console')//？？

app.use(serveFavicon('favicon.ico'))
//-------------------------------------------------------//
app.use(function (req, res, next) { //next: 下一个
    let d = new Date()
    let year = d.getFullYear()
    let month = d.getMonth() + 1
    let day = d.getDate()
    let h = d.getHours()
    let m = d.getMinutes()
    let s = d.getSeconds()
    req.time = ` ${year}年${month}月${day}日 ${h}：${m}：${s}`
    next()
})
//----------------------------------------------------
app.get('/login', (req, res) => {
    let filepath = path.join(__dirname, 'views/login.html')
    res.sendFile(filepath)
})

app.get('/register', (req, res) => {
    let filepath = path.join(__dirname, 'views/register.html')
    res.sendFile(filepath)
})
//////////////////////////////////////////////////////////////////
app.post('/login', (req, res) => {
    let sj = fs.readFileSync('./person.json', 'utf8') //字符串形式
    let w = JSON.parse(sj) //转对象
    let tf = w.findIndex(item => item.username == req.body.tel && item.password == req.body.pass)
    if (tf == -1) {
        res.send('<h1>登陆失败</h1>')
    } else {
        res.send('<h1>登录成功</h1>')
    }
})
app.post('/doregister', (req, res) => {
    let sj = fs.readFileSync('./person.json', 'utf8') //字符串形式
    let w = JSON.parse(sj) //转对象


    let tf = w.find(item => item.username == req.body.tel)

    if (tf) {
        res.send("该账号已注册")
    } else if (!req.body.tel.replace(/^\s+|\s+$/, '')) {
        res.send("请输入用户名")
    } else if (!req.body.pass.replace(/^\s+|\s+$/, '')) {
        res.send("请输入密码")
    } else if (req.body.pass.replace(/^\s+|\s+$/, '') != req.body.pass2.replace(/^\s+|\s+$/, '')) {
        res.send("请输入密码")
    } else {
        let tel = req.body.tel
        let pass = req.body.pass
        let time = req.time

        w.push({ tel, pass, time })
        fs.writeFileSync("persons.json", w, { flag: "w" });
        res.send("注册成功")
    }
})

